package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.mail.MessagingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import top.hepingan.java.common.Result;
import top.hepingan.java.dto.OrderImgDto;
import top.hepingan.java.entity.Orders;
import top.hepingan.java.entity.OrdersImage;
import top.hepingan.java.exceptions.RegistrationException;
import top.hepingan.java.mapper.OrdersImageMapper;
import top.hepingan.java.mapper.OrdersMapper;
import top.hepingan.java.utils.AliUploadUtils;
import top.hepingan.java.utils.BeanUtils;
import top.hepingan.java.utils.UserUtils;
import top.hepingan.java.vo.OrdersVo;
import org.thymeleaf.context.Context;
import jakarta.mail.internet.MimeMessage;



import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/order")
@RestController
@Slf4j
@RequiredArgsConstructor
public class OrdersController {

    private final OrdersMapper ordersMapper;
    private final OrdersImageMapper ordersImageMapper;
    private final AliUploadUtils aliUploadUtils;
    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String username;

    @PostMapping("/add")
    public Result order(@RequestBody OrdersVo ordersVo) {
        Orders orders = BeanUtils.copyClassProperTies(ordersVo, Orders.class);
        ordersMapper.insert(orders.setStatus("待处理")
                .setCreatedTime(LocalDateTime.now())
                .setUserId(UserUtils.getCurrentLoginId()));
        for (String image : ordersVo.getImageList()){
            ordersImageMapper.insert(new OrdersImage().setOrdersId(orders.getId()).setImgUrl(image));
        }

        final String code = ordersVo.getTitle()+",内容:"+ordersVo.getContent();
        Context context = new Context();
        context.setVariable("code", code);
        String email = "1973016127@qq.com";
        String process = templateEngine.process("emailCode.html", context);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("浩原科技小程序新订单");
            helper.setFrom(username);
            helper.setTo(email);
            helper.setSentDate(new Date());
            helper.setText(process, true);
            new Thread(() -> mailSender.send(mimeMessage)).start();
        } catch (MessagingException e) {
            throw new RegistrationException("邮箱发送失败|订单已添加", 500);
        }
        return Result.ok();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Long id) {
        Orders orders = ordersMapper.selectById(id);
        List<OrdersImage> ordersImages = ordersImageMapper.selectList(new QueryWrapper<OrdersImage>().lambda().eq(OrdersImage::getOrdersId, id));
        List<String> imageList = new ArrayList<>();
        ordersImages.forEach(ordersImage -> imageList.add(ordersImage.getImgUrl()));
        return Result.data(BeanUtils.copyClassProperTiesWriteDate(orders, OrdersVo.class).setImageList(imageList));
    }

    @GetMapping("/myList")
    public Result myList(@RequestParam Integer pageNum) {
        List<Orders> records = ordersMapper.selectPage(new Page<>(pageNum, 20), new QueryWrapper<Orders>().lambda().orderByDesc(Orders::getCreatedTime)
                .eq(Orders::getUserId, UserUtils.getCurrentLoginId())).getRecords();
        List<OrdersVo> ordersVoList = new ArrayList<>();
        records.forEach(orders -> {
            List<OrdersImage> ordersImages = ordersImageMapper.selectList(new QueryWrapper<OrdersImage>().lambda().eq(OrdersImage::getOrdersId, orders.getId()));
            List<String> imageList = new ArrayList<>();
            ordersImages.forEach(ordersImage -> imageList.add(ordersImage.getImgUrl()));
            ordersVoList.add(BeanUtils.copyClassProperTiesWriteDate(orders, OrdersVo.class).setImageList(imageList));
        });
        return Result.data(ordersVoList);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Orders orders) {
        ordersMapper.updateById(orders);
        return Result.ok();
    }

    @PostMapping("/cancel")
    public Result delete(@RequestBody Long id) {
        ordersMapper.updateById(new Orders().setId(id).setStatus("已取消"));
        return Result.ok();
    }

    @PostMapping("/deleteImg")
    public Result deleteImg(@RequestBody OrderImgDto orderImgDto) {
        aliUploadUtils.deleteFileByUrl(orderImgDto.getImgUrl());
        ordersImageMapper.delete(new QueryWrapper<OrdersImage>().lambda()
                .eq(OrdersImage::getImgUrl, orderImgDto.getImgUrl())
                .eq(OrdersImage::getOrdersId, orderImgDto.getId()));
        return Result.ok();
    }

    @PostMapping("/addImg")
    public Result addImg(@RequestBody OrderImgDto orderImgDto) {
        ordersImageMapper.insert(new OrdersImage().setOrdersId(orderImgDto.getId()).setImgUrl(orderImgDto.getImgUrl()));
        return Result.ok();
    }
}
